package com.sls.nzdapplication.ui.custom;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hmy.popwindow.PopItemAction;
import com.hmy.popwindow.PopWindow;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.db.utils.DyEquipmentUtil;
import com.sls.nzdapplication.db.utils.EquipmentUtil;
import com.sls.nzdapplication.db.utils.GyyhdUtil;
import com.sls.nzdapplication.db.utils.MeterBoxUtil;
import com.sls.nzdapplication.db.utils.StationAreaUtil;
import com.sls.nzdapplication.db.utils.WorkLineUtil;
import com.sls.nzdapplication.model.DyEquipment;
import com.sls.nzdapplication.model.Equipment;
import com.sls.nzdapplication.model.Gyyhd;
import com.sls.nzdapplication.model.MeterBox;
import com.sls.nzdapplication.model.StationArea;
import com.sls.nzdapplication.model.WorkLine;
import com.sls.nzdapplication.app.MySharedPreferences;
import com.sls.nzdapplication.ui.activity.PhotoDetailActivity;
import com.sls.nzdapplication.ui.widget.OnItemClickListener;
import com.sls.nzdapplication.ui.widget.OnItemLongClickListener;
import com.sls.nzdapplication.util.DeviceUtils;
import com.sls.nzdapplication.util.GetImgPath;
import com.sls.nzdapplication.util.ImageUtil;
import com.sls.nzdapplication.util.Utils;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import es.dmoral.toasty.Toasty;

public class CableWellPhotoView extends RelativeLayout implements View.OnClickListener, OnItemClickListener, OnItemLongClickListener {
    private TextView titleView;
    private RecyclerView photoWallView;
    private ImageView addPhoto;
    private Uri mImageUri;                                  //指定的uri

    private String mImageName;                              //保存的图片的名字

    private File mImageFile;
    private String mImagePath;

    private String myImageID = "";

    private String phoneType = "";

    private String dataType = "";

    private String content = "";

    private PhotoWallAdapter photoWallAdapter;

    private OnclickPhotoListener onclickPhotoListener;

    private Activity mActivity = null;

    private String photoTypeName;




    public static final String SD_APP_DIR_NAME = "NZDAPP"; //存储程序在外部SD卡上的根目录的名字
    public static final String PHOTO_DIR_NAME = "Cablewell";
    public static final int PHOTO_RESULT_CODE = 100;
    public static final int IMAGE_REQUEST_CODE = 200;

    private List<String> imageList = new ArrayList<>();;

    public CableWellPhotoView(Context context) {
        super(context);
    }

    public CableWellPhotoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CableWellPhotoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化布局
        ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.cable_well_photo_view_layout, this, true);
        initView();
        initFromAttributes(context,attrs);
        setListener();
    }

    private void initFromAttributes(Context context, @Nullable AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CableWellPhotoView);
        String title = ta.getString(R.styleable.CableWellPhotoView_cpTitle);
        setTitleText(title);
    }

    public void setOnclickPhotoListener(OnclickPhotoListener onclickPhotoListener){
        this.onclickPhotoListener = onclickPhotoListener;
    }

    /**
     * 照片文字
     *
     * @param text
     */
    public void setTitleText(String text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        titleView.setVisibility(View.VISIBLE);
        titleView.setText(text);
    }

    private void initView(){
        titleView = findViewById(R.id.photo_title);
        photoWallView = findViewById(R.id.photo_wall);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        photoWallView.setLayoutManager(linearLayoutManager);
        addPhoto = findViewById(R.id.add_photo);

    }

    private void setListener(){
        addPhoto.setOnClickListener(this);


    }

    private void refreshPhoto(){
        imageList.clear();
        imageList.addAll(Utils.getFilesAllName(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/" + SD_APP_DIR_NAME + "/" + dataType + "/"+myImageID+"/"+phoneType+"/"));
        photoWallAdapter.notifyDataSetChanged();

    }

    public void initData(String dType,String id,String pType){
        this.dataType = dType;
        this.myImageID = id;
        this.phoneType = pType;


        imageList = Utils.getFilesAllName(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/" + SD_APP_DIR_NAME + "/" + dataType + "/"+myImageID+"/"+phoneType+"/");


        photoWallAdapter = new PhotoWallAdapter(imageList);
        photoWallView.setAdapter(photoWallAdapter);
        photoWallAdapter.setOnItemClickListener(this);
        photoWallAdapter.setOnItemLongClickListener(this);


        if(pType.equals("qm")){
            this.photoTypeName = "全貌照片";
        }else if(pType.equals("mp")){
            this.photoTypeName = "铭牌照片";
        }
        else if(pType.equals("qx")){
            this.photoTypeName = "缺陷照片";
        }
        else if(pType.equals("dk")){
            this.photoTypeName = "打开照片";
        }
        else if(pType.equals("gb")){
            this.photoTypeName = "关闭照片";
        }
        else if(pType.equals("qt")){
            this.photoTypeName = "其他照片";
        }
        else if(pType.equals("gp")){
            this.photoTypeName = "钢牌照片";
        }
        else if(pType.equals("gps")){
            this.photoTypeName = "GPS定位照片";
        }
        else if(pType.equals("zsq")){
            this.photoTypeName = "故障指示器照片";
        }
        else if(pType.equals("blq")){
            this.photoTypeName = "避雷器照片";
        }

        else{
            this.photoTypeName = "其他照片";
        }

    }

    public void setmActivity(Activity activity){
        this.mActivity = activity;
    }

    /**
     * 创建图片文件
     */
    private void createImageFile(){
        //设置图片文件名（含后缀），以当前时间的毫秒值为名称
        mImageName =  Calendar.getInstance().getTimeInMillis() + ".jpg";

        //创建图片文件
        mImageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/" + SD_APP_DIR_NAME + "/" + dataType + "/"+myImageID+"/"+phoneType+"/", mImageName);
        //将图片的绝对路径设置给mImagePath，后面会用到
        mImagePath = mImageFile.getAbsolutePath();
        //按设置好的目录层级创建
        mImageFile.getParentFile().mkdirs();

        //不加这句会报Read-only警告。且无法写入SD
        mImageFile.setWritable(true);
    }



    /**
     * 启动相机，创建文件，并要求返回uri
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void startCamera() {
        Intent intent = new Intent();
        //指定动作，启动相册
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        //创建文件
        createImageFile();
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //获取uri
        mImageUri = FileProvider.getUriForFile(getContext(), "com.sls.nzdapplication.provider", mImageFile);
        System.err.println(mImageUri);
        //将uri加入到额外数据
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        //启动相机并要求返回结果
        if(mActivity!=null){
            mActivity.startActivityForResult(intent, PHOTO_RESULT_CODE);
        }else{
            ((Activity) getContext()).startActivityForResult(intent, PHOTO_RESULT_CODE);
        }


    }
    /**
     * 启动相册，创建文件，并要求返回uri
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void startImageFile() {
        Intent intent = new Intent();
        //指定动作，启动相机
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        //创建文件
        createImageFile();
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //获取uri
        mImageUri = FileProvider.getUriForFile(getContext(), "com.sls.nzdapplication.provider", mImageFile);
        //将uri加入到额外数据
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        //启动相机并要求返回结果

        if(mActivity!=null){
            mActivity.startActivityForResult(intent, IMAGE_REQUEST_CODE);
        }else{
            ((Activity) getContext()).startActivityForResult(intent, IMAGE_REQUEST_CODE);
        }


    }

    private boolean initContent(){
        System.err.println(dataType);
        this.content = "";
        if(dataType.equals("Equipment")){
            EquipmentUtil equipmentUtil = new EquipmentUtil(getContext());
            Equipment eq = equipmentUtil.listOneEquipment(this.myImageID);
            GyyhdUtil gyyhdUtil = new GyyhdUtil(getContext());
            Gyyhd gyyhd = gyyhdUtil.listOneGyyhd(this.myImageID);

            if(eq==null && gyyhd == null){
                return false;
            }
            if(eq != null){
                WorkLineUtil workLineUtil = new WorkLineUtil(getContext());
                WorkLine workLine = workLineUtil.listOneWorkLine(eq.getWorkLineId());
                this.content += workLine.getName()+"\n";
//                this.content += eq.getName()+this.photoTypeName+"\n";
                this.content += "经度:"+String.format("%.8f", eq.getLon())+"\n";
                this.content += "纬度:"+String.format("%.8f", eq.getLat())+"\n";
                this.content += "地址:"+new MySharedPreferences(getContext()).getAddress()+"\n";
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//                Date date = new Date(System.currentTimeMillis());
//                this.content += simpleDateFormat.format(date)+"\n";
                this.content += "缺陷:"+eq.getQxxx();
            }else{
                WorkLineUtil workLineUtil = new WorkLineUtil(getContext());
                WorkLine workLine = workLineUtil.listOneWorkLine(gyyhd.getAreaId());
                this.content += workLine.getName()+"\n";
//                this.content += gyyhd.getName()+this.photoTypeName+"\n";
                this.content += "经度:"+String.format("%.8f", gyyhd.getLon())+"\n";
                this.content += "纬度:"+String.format("%.8f", gyyhd.getLat())+"\n";
                this.content += "地址:"+new MySharedPreferences(getContext()).getAddress()+"\n";
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//                Date date = new Date(System.currentTimeMillis());
//                this.content += simpleDateFormat.format(date)+"\n";
                this.content += "缺陷:";
            }
        }else if(dataType.equals("dyEquipment")){
            DyEquipmentUtil dequipmentUtil = new DyEquipmentUtil(getContext());
            DyEquipment eq = dequipmentUtil.listOneDyEquipment(this.myImageID);
            if(eq==null){
                return false;
            }
            StationAreaUtil stationAreaUtil = new StationAreaUtil(getContext());
            StationArea stationArea = stationAreaUtil.listOneStationArea(eq.getAreaId());
            this.content += stationArea.getName()+"\n";
//            this.content += eq.getName()+this.photoTypeName+"\n";
            this.content += "经度:"+String.format("%.8f", eq.getLon())+"\n";
            this.content += "纬度:"+String.format("%.8f", eq.getLat())+"\n";
            this.content += "地址:"+new MySharedPreferences(getContext()).getAddress()+"\n";
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//            Date date = new Date(System.currentTimeMillis());
//            this.content += simpleDateFormat.format(date)+"\n";
            this.content += "缺陷:"+eq.getQxxx();
        }
        else if(dataType.equals("MeterBox")){
            MeterBoxUtil meterBoxUtil = new MeterBoxUtil(getContext());
            MeterBox eq = meterBoxUtil.listOneMeterBox(this.myImageID);
            if(eq==null){
                return false;
            }
            StationAreaUtil stationAreaUtil = new StationAreaUtil(getContext());
            StationArea stationArea = stationAreaUtil.listOneStationArea(eq.getAreaId());
            this.content += stationArea.getName()+"\n";
//            this.content += eq.getBoxCode()+this.photoTypeName+"\n";
            this.content += "经度:"+String.format("%.8f", eq.getLon())+"\n";
            this.content += "纬度:"+String.format("%.8f", eq.getLat())+"\n";
            this.content += "地址:"+new MySharedPreferences(getContext()).getAddress()+"\n";
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//            Date date = new Date(System.currentTimeMillis());
//            this.content += simpleDateFormat.format(date)+"\n";
            this.content += "缺陷:"+eq.getQxxx();
        }
        else if(dataType.equals("Area")){
            StationAreaUtil stationAreaUtil = new StationAreaUtil(getContext());
            StationArea stationArea = stationAreaUtil.listOneStationArea(this.myImageID);
            if(stationArea==null){
                return false;
            }
            this.content += stationArea.getName()+"\n";
//            this.content += stationArea.getName()+this.photoTypeName+"\n";
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//            Date date = new Date(System.currentTimeMillis());
//            this.content += simpleDateFormat.format(date)+"\n";
        }
        return true;
    }

    /**
     * 保存照片到SD卡的指定位置
     */
    private void savePhotoToSD(Bitmap bitmap) {
        if(dataType.equals("MeterBox")){
            bitmap = ImageUtil.drawTextToLeftBottom(getContext(),bitmap,this.content,18, getContext().getResources().getColor(R.color.white),5,200);

        }else{
            bitmap = ImageUtil.drawTextToLeftBottom(getContext(),bitmap,this.content,32, getContext().getResources().getColor(R.color.white),5,300);
        }
        //创建输出流缓冲区
        BufferedOutputStream os = null;
        try {
            //设置输出流
            os = new BufferedOutputStream(new FileOutputStream(mImageFile));
            //压缩图片，100表示不压缩
            bitmap.compress(Bitmap.CompressFormat.JPEG, 65, os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    //不管是否出现异常，都要关闭流
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 更新系统图库
     */
    private void updateSystemGallery() {
        //把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(getContext().getContentResolver(),
                    mImageFile.getAbsolutePath(), mImageName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + mImagePath)));
    }

    @Override
    public void onItemClick(View v, int position) {
        if(onclickPhotoListener!=null){
            onclickPhotoListener.openPhotoView(imageList.get(position));
        }
    }

    @Override
    public void onItemLongClick(View v, int position) {
        clearPhotoData(position);
    }

    private void clearPhoto(int postion){
        File file = new File(imageList.get(postion));
        if(file!=null){
            file.delete();
        }
        refreshPhoto();
    }

    private void clearPhotoData(int postion){
        if(mActivity!=null){
            new PopWindow.Builder(mActivity)
                    .setStyle(PopWindow.PopWindowStyle.PopUp)
                    .setTitle("你确定要删除该照片吗？")
                    .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                        @Override
                        public void onClick() {
                            clearPhoto(postion);
                            Toast.makeText(getContext(),"清除成功",Toast.LENGTH_SHORT).show();
                        }
                    }))
                    .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                    .show();
        }else{
            new PopWindow.Builder((Activity) getContext())
                    .setStyle(PopWindow.PopWindowStyle.PopUp)
                    .setTitle("你确定要删除该照片吗？")
                    .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                        @Override
                        public void onClick() {
                            clearPhoto(postion);
                            Toast.makeText(getContext(),"清除成功",Toast.LENGTH_SHORT).show();
                        }
                    }))
                    .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                    .show();
        }

    }

    public void onActivityResultListener(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PHOTO_RESULT_CODE: {
                    Bitmap bitmap = null;
                    try {
                        //根据uri设置bitmap
                        bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), mImageUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //将图片保存到SD的指定位置
                    savePhotoToSD(bitmap);
                    //更新系统图库
                    updateSystemGallery();
                    refreshPhoto();
                    break;
                }
                case IMAGE_REQUEST_CODE:{
                    final File imgFile = new File(GetImgPath.getPath(getContext(), data.getData()));
                    Utils.copyFile(imgFile.getPath(),mImagePath);
                    refreshPhoto();
                    break;
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        if(view == addPhoto){
            if(onclickPhotoListener!=null){
                onclickPhotoListener.onClickPhotoListener(phoneType);
            }
            if(!initContent()){
                Toasty.info(getContext(),"请先保存数据",Toast.LENGTH_SHORT,true).show();
                return;
            }
            openMenu();

        }
    }
    private void openMenu(){
//        startCamera();
        if(mActivity !=null){
            new PopWindow.Builder(mActivity)
                    .setStyle(PopWindow.PopWindowStyle.PopAlert)
                    .setMessage("请选择照片方式")
                    .setIsShowCircleBackground(false)
                    .addItemAction(new PopItemAction("拍照", new PopItemAction.OnClickListener() {
                        @Override
                        public void onClick() {
                            startCamera();
                        }
                    }))
                    .addItemAction(new PopItemAction("相册", new PopItemAction.OnClickListener() {
                        @Override
                        public void onClick() {
                            startImageFile();
                        }
                    }))
                    .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                    .setPopWindowMarginsF(DeviceUtils.dip2px4View(getContext(),30), DeviceUtils.dip2px4View(getContext(),300), DeviceUtils.dip2px4View(getContext(),30), DeviceUtils.dip2px4View(getContext(),0))
                    .show();
        }else{
            new PopWindow.Builder((Activity) getContext())
                    .setStyle(PopWindow.PopWindowStyle.PopAlert)
                    .setMessage("请选择照片方式")
                    .setIsShowCircleBackground(false)
                    .addItemAction(new PopItemAction("拍照", new PopItemAction.OnClickListener() {
                        @Override
                        public void onClick() {
                            startCamera();
                        }
                    }))
                    .addItemAction(new PopItemAction("相册", new PopItemAction.OnClickListener() {
                        @Override
                        public void onClick() {
                            startImageFile();
                        }
                    }))
                    .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                    .setPopWindowMarginsF(DeviceUtils.dip2px4View(getContext(),30), DeviceUtils.dip2px4View(getContext(),300), DeviceUtils.dip2px4View(getContext(),30), DeviceUtils.dip2px4View(getContext(),0))
                    .show();
        }

    }

    private class PhotoWallAdapter extends RecyclerView.Adapter<CableWellPhotoView.ItemPhotoViewHolder> {
        private List<String> imageUrls;
        private OnItemClickListener onItemClickListener;
        private OnItemLongClickListener onItemLongClickListener;

        public PhotoWallAdapter(List<String> imageUrls) {
            this.imageUrls = imageUrls;
        }

        public void setOnItemClickListener(OnItemClickListener onItemClickListener){
            this.onItemClickListener = onItemClickListener;
        }

        public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener){
            this.onItemLongClickListener = onItemLongClickListener;
        }

        @NonNull
        @Override
        public CableWellPhotoView.ItemPhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = ((LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                    .inflate(R.layout.phtot_item_layout, parent, false);
            return new CableWellPhotoView.ItemPhotoViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull CableWellPhotoView.ItemPhotoViewHolder holder,int position) {
            System.err.println(position);
            File file = new File(imageUrls.get(position));
            Uri uri = Uri.fromFile(file);
            ContentResolver cr = getContext().getContentResolver();
            try {
                //根据Uri获取流文件
                InputStream is = cr.openInputStream(uri);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize =3;
                Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
                holder.imageView.setImageBitmap(bitmap);
                holder.imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(onItemClickListener==null){
                            return;
                        }
                        onItemClickListener.onItemClick(view,position);
                    }
                });

                holder.imageView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        if(onItemLongClickListener !=null){
                            onItemLongClickListener.onItemLongClick(view,position);
                        }
                        return false;
                    }
                });
            }
            catch(Exception e)
            {
            }
        }

        @Override
        public int getItemCount() {
            if(imageUrls == null){
                return 0;
            }
            return imageUrls.size();
        }
    }

    private class ItemPhotoViewHolder extends RecyclerView.ViewHolder{
        private ImageView imageView;


        public ItemPhotoViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.item_photo);
        }
    }

    public interface OnclickPhotoListener{
        void onClickPhotoListener(String type);

        void openPhotoView(String path);
    }
}
